const express = require("express");
const moment = require("moment");
const fs = require("./libs/FileHelper")
const db = require("./libs/DBHelper");
const cors = require("cors");
const { response, request } = require("express");

let server = express();
server.use(express.static("./../src"))

//支持post请求
server.use(express.urlencoded({ extended: false }));
server.use(express.json())

//拦截器
server.use(cors());

//post 登录
server.post("/api/login", async function (requset, response, next) {
    //1.编写前端发送过来的数据
    let ouser = requset.body;
    console.log(ouser);
    //2.编写sql语句
    let sql = "SELECT `id`,`name`,`pwd`,`phone` FROM `users` WHERE name=? AND pwd=? AND `status`=1;"
    //3.执行sql语句
    let res = await db.exec(sql, [ouser.name, ouser.pwd, ouser.status])
    //4.获取结果
    let osmg = {
        message: "登录失败",
        code: -1,
        status: 0
    }
    if (res && res.length >= 1) {
        osmg["message"] = "登陆成功";
        osmg["code"] = 1;
        osmg["status"] = 1;
        //提示当前登陆者的信息
        osmg["data"] = res[0];
    }
    //把信息丢出去
    response.json(osmg)

});


// post 注册
// name pwd pwd1  phone creatime
server.post("/api/reg", async function (requset, response, next) {
    let ouser = requset.body;
    console.log(ouser);
    let msg = {
        message: "注册成功",
        code: 200
    }
    let params = [
        ouser.name,
        ouser.pwd,
        ouser.phone,
        moment(Date.now()).format("YYYY-MM-DD hh:mm:ss")
    ];
    if (ouser.pwd != ouser.pwd1) {
        msg.message = "两次密码输入不一致";
        msg.code = -201
        response.json(msg);
    }

    try {
        let sql = "INSERT INTO users(name,pwd,phone,craetime) VALUES(?,?,?,?);"
        let res = await db.exec(sql, params);
        // console.log(res);
        let flag = res && res.affectedRows >= 1;
        if (!flag) {
            msg = {
                message: "注册失败",
                code: -201
            }
        }
        response.json(msg);
    } catch (error) {
        response.json({ message: "注册失败1", err: error.message, code: -201 })
    }

})

//获取所有的商品
server.get("/api/prod", async (request, response, next) => {

    let data = JSON.parse(await fs.getFile("./data/production.json"));
    response.json({
        msg: "查询成功",
        code: 200,
        data
    })

})

//根据 id查询对应的
server.get("/api/prodinfo", async (request, response, next) => {
    // let uid = request.params.id;
    // let data = JSON.parse(await fs.getFile("./data/production.json"));
    // let res = data.find(el => el.id == uid);
    // response.json({
    //     msg: "查询成功",
    //     code: 200,
    //     data: res
    // });

    let querysql = "SELECT * FROM `carts` WHERE `status`=1";
    let res = await db.exec(querysql);
    response.json(res)
})


//购物车
server.post("/api/addcart", async (request, response, next) => {
    let params = [
        request.body.id,
        request.body.name,
        request.body.goodsCount,
        request.body.imgUrl,
        request.body.price,
        request.body.goodsParams,
        request.body.singleGoodsMoney
    ]
    let querysql = "SELECT * FROM `carts` WHERE `id`=? AND `name`=? AND `status`=1;"
    let res = await db.exec(querysql, params);
    let status1 = (res && res.length >= 1);
    if (status1) {
        let datasql = "UPDATE `carts` SET `goodsCount`= goodsCount+1 , `singleGoodsMoney` =  price*goodsCount   WHERE id = ? AND `name` = ? AND `status`=1;"
        let res = await db.exec(datasql, params);
        let status = (res && res.affectedRows >= 1); //修改成功
        response.json({
            message: status ? "加入购物车成功u" : "加入购物车失败u",
            code: status ? 200 : -200
        })
    } else {
        //插入
        let params1 = [
            request.body.id,
            request.body.name,
            request.body.price,
            request.body.goodsCount,
            request.body.imgUrl,
            request.body.goodsParams,
            (Number(request.body.goodsCount) * Number(request.body.price)).toFixed(1),
            moment().format("YYYY-MM-DD hh:mm:ss")
        ];
        console.log(params1);
        let insetsql = "INSERT INTO `carts` (`id`,`name`, `price`,`goodsCount`, `imgurl`,`goodsparmas`, `singleGoodsMoney`, `creatime`) VALUES(?,?,?,?,?,?,?,?)";
        let res = await db.exec(insetsql, params1);
        let status = (res && res.affectedRows >= 1);

        response.json({
            message: status ? "加入购物车成功i" : "加入购物车失败",
            code: status ? 200 : -200
        })
    }
})



//删除购物车
server.post("/api/delect", async (request, response, next) => {
    let params = [
        request.body.id
    ]
    let datasql = "UPDATE `carts` SET `status`=0  WHERE id = ?"
    let res = await db.exec(datasql, params);
    let status = (res && res.affectedRows >= 1)
    response.json({
        message: status ? "删除成功" : "删除失败",
        code: status ? 200 : -200
    })
})

// 购物车 接口
/* server.post("/api/addcart", async (request, response, next) => {
    let params = [
        request.body.id,
        request.body.name
    ]
    let querysql = "SELECT * FROM `carts` WHERE `id`=? AND `name`=? AND `status`=1;"
    let res = await db.exec(querysql, params)
    let status1 = (res && res.length >= 1);
    if (status1) {
        //修改
        let pardata = [
            request.body.id,
            request.body.name,
            request.body.goodsCount
        ]
        let datasql = "UPDATE `carts` SET `goodsCount`= goodsCount+? , singleGoodsMoney =  price*goodsCount  WHERE id = ? AND `name` = ? AND `status`=1;"
        let res = await db.exec(datasql, pardata);
        //更新 删除 修改手影响的行数
        let status = (res && res.affectedRows >= 1); //修改成功
        response.json({
            message: status ? "加入购物车成功u" : "加入购物车失败u",
            code: status ? 200 : -200
        })
    } else {
        //插入
        let params1 = [
            request.body.id,
            request.body.name,
            request.body.price,
            request.body.goodsCount,
            request.body.imgurl,
            request.body.goodsparmas,
           (Number( request.body.goodsCount) * Number(request.body.price)).toFixed(1),
            moment().format("YYYY-MM-DD hh:mm:ss")
        ];
        let insetsql = "INSERT INTO `carts` (`id`,`name`,`price`,`goodsCount`,`imgurl`,`goodsparmas`,`singleGoodsMoney`, `creatime`) VALUES(?,?,?,?,?,?,?,?)"
        console.log(params1);
        let res = await db.exec(insetsql, params1);
        let status = (res && res.affectedRows >= 1);

        response.json({
            message: status ? "加入购物车成功i" : "加入购物车失败",
            code: status ? 200 : -200
        })
    }
})
 */








server.listen(8080, () => {
    console.log("服务器启动完毕了1!");
})